﻿using JinfuyuanProject.Entity;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace JinfuyuanProject.Repository
{
    public class MailBoxRepository: IMailBoxRepository
    {
        public List<MessageInfo> GetData()
        {
            using (var sqlconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Jinfuyuan2025"].ConnectionString))
            {
                sqlconnection.Open();
                using (SqlCommand cmd = new SqlCommand($"SELECT StaffSendId,Contents,IsRead,Times,IsDelete,Href FROM dbo.MessageInfo", sqlconnection))
                {
                    cmd.Notification = null;
                    //SQL依赖对象
                    SqlDependency dependency = new SqlDependency(cmd);
                    //事件
                    dependency.OnChange += new OnChangeEventHandler(dependency_Onchange);
                    if (sqlconnection.State == ConnectionState.Closed)
                        sqlconnection.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    List<MessageInfo> list = new List<MessageInfo>();
                    while (reader.Read())
                    {
                        MessageInfo m = new MessageInfo();
                        m.StaffSendId = Convert.ToInt32(reader["StaffSendId"]);
                        m.Contents = Convert.ToString(reader["Contents"]);
                        m.IsRead = Convert.ToInt32(reader["IsRead"]);
                        m.Times = reader["Times"] as DateTime?;
                        m.IsDelete= Convert.ToInt32(reader["IsDelete"]);
                        m.Href = Convert.ToString(reader["Href"]);
                        list.Add(m);
                    }
                    return list;
                }

            }
        }
        public void dependency_Onchange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                //广播推送
                IHubContext chat = GlobalHost.ConnectionManager.GetHubContext("mailboxChatHub");
                chat.Clients.All.RevMail(Newtonsoft.Json.JsonConvert.SerializeObject(GetData()));
            }

        }
    }
}
